﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFMINERP.DAL;

using WCFMINERP.Contracts;
using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.COM;
using System.IO;

namespace WCFMINERP.BLL.TransferBLL
{
    public class TransferFilesServiceBLL
    {

        //public delegate void SHOWFILEINFO(UploadInfo file, int type);//0添加到等待列表1更改现有的进度3完成任务在列表中删除

        //public event SHOWFILEINFO ShowFile;//定义操作事件
        
        //public 



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool Add(UploadQueueInfo info)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<UploadQueue> listQueue = db.UploadQueue.Where(p => p.Shop.ShopId == info.ShopId && p.ZipName == info.ZipName && p.Status == (int)TransferStatus.Done).ToList();
                if (listQueue != null && listQueue.Count > 0) //已经存在
                {
                    return false;
                }


                UploadQueue queueModel = new UploadQueue();
                queueModel.CreateTime = info.CreateTime;
                queueModel.FileLength = Convert.ToInt32(info.FileLength);
                queueModel.Shop = db.Shop.FirstOrDefault(f => f.ShopId == info.ShopId);               
                queueModel.ShopName = info.ShopName;
                queueModel.Status = info.Status;
                queueModel.ZipName = info.ZipName;
                queueModel.MachineName = info.MachineName;
                queueModel.ShoptempPath = info.ShoptempPath;
                queueModel.CompleteTime = info.CompleteTime;
                queueModel.Remark = info.Remark;
                queueModel.orderbagid = info.orderbagid;
                queueModel.CompleteTime = Convert.ToDateTime("1911-1-1");
                               

                db.UploadQueue.AddObject(queueModel);
                db.SaveChanges();
                if (queueModel.UploadId == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        /// <summary>
        /// 获取下载暂存目录
        /// </summary>
        /// <returns></returns>
        public string GetSavePath()
        {
            string path = string.Empty;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                return db.FileDirPath.FirstOrDefault(ph => ph.Des == "下载目录").FileDir;

            }
        }
        
        /// <summary>
        /// 获取正在上传的文件
        /// </summary>
        /// <returns></returns>
        public List<TransferFileInfo> GetTransferingData()
        {
            int transferingStatus = (int)OrderBag_AutoStatus.Transfering;
            List<TransferFileInfo> listbag = new List<TransferFileInfo>();
            //using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            //{
            //    List<tb_OrderBag_Auto> orderbaglist = db.tb_OrderBag_Auto.Where(bag => bag.Status == transferingStatus).ToList();
            //    foreach (tb_OrderBag_Auto orderbag in orderbaglist)
            //    {
            //        TransferFileInfo info = new TransferFileInfo();
            //        info.FetchTime = orderbag.FetchTime;
            //        info.OrderbagID = orderbag.OrderbagID;
            //        info.OrderbagName = orderbag.OrderbagName;
            //        info.OrderTime = orderbag.OrderTime;
            //        info.PrePriceCount = orderbag.PrePriceCount;
            //        info.Priority = orderbag.Priority;
            //        info.RARName = orderbag.RARName;
            //        info.Remark = orderbag.Remark;
            //        info.SerialNum = orderbag.SerialNum;
            //        info.ShopId = orderbag.ShopId;
            //        info.Status = orderbag.Status;
            //        info.ShopName = db.Shop.FirstOrDefault(p => p.ShopId == orderbag.ShopId).shopName;
            //        listbag.Add(info);
            //    }

            //}
            return listbag;
        }

        /// <summary>
        /// 根据文件名称获取文件
        /// </summary>
        /// <param name="inStrName"></param>
        /// <returns></returns>
        public TransferFileInfo GetTransferingDataByName(string inStrName)
        {
            TransferFileInfo rtninfo = new TransferFileInfo();
            //using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            //{
            //    tb_OrderBag_Auto orderbag = db.tb_OrderBag_Auto.FirstOrDefault(bag => bag.RARName == inStrName);

            //    if (orderbag == null)
            //    {
            //        return new TransferFileInfo();
            //    }
            //    TransferFileInfo info = new TransferFileInfo();
            //    info.FetchTime = orderbag.FetchTime;
            //    info.OrderbagID = orderbag.OrderbagID;
            //    info.OrderbagName = orderbag.OrderbagName;
            //    info.OrderTime = orderbag.OrderTime;
            //    info.PrePriceCount = orderbag.PrePriceCount;
            //    info.Priority = orderbag.Priority;
            //    info.RARName = orderbag.RARName;
            //    info.Remark = orderbag.Remark;
            //    info.SerialNum = orderbag.SerialNum;
            //    info.ShopId = orderbag.ShopId;
            //    info.Status = orderbag.Status;
            //    info.ShopName = db.Shop.FirstOrDefault(p => p.ShopId == orderbag.ShopId).shopName;


            //}
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                tb_OrderBag_Auto orderbag = db.tb_OrderBag_Auto.FirstOrDefault(bag => bag.RARName == inStrName);

            }

            return rtninfo;
        }
        /// <summary>
        /// 检查是否开过单
        /// </summary>
        /// <param name="inZipName"></param>
        /// <returns>true </returns>
        public bool CheckZipRepeated(string inZipName)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                tb_OrderBag_Auto orderbag = db.tb_OrderBag_Auto.FirstOrDefault(pt => pt.RARName == inZipName);
                if (orderbag == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        /// <summary>
        ///初始化连接返回是否口可以上传
        /// </summary>
        /// <param name="inFileName"></param>
        /// <returns></returns>
        public TransferFileInfo InitTransferFile(TransferFileInfo ininfo, int inMaxQueueNum)
        {
            string inFileName = ininfo.Name;
            Int64 inFileLength = ininfo.Length;
            TransferFileInfo rtnInfo = new TransferFileInfo();
            int intDiong = (int)TransferStatus.Doing;
            int intWait = (int)TransferStatus.Wait;
            int intStop = (int)TransferStatus.Stop;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                //检查列表中是否存在
                UploadQueue queue = db.UploadQueue.FirstOrDefault(p => p.ZipName == inFileName);
                if (queue != null)//上传列表已经存在
                {
                    if (queue.Status == intDiong)//可以上传中断后继续上传的
                    {
                        rtnInfo = new TransferFileInfo() { Name = inFileName, Status = intDiong, CreateTime = queue.CreateTime, Length = queue.FileLength, ShopName = queue.ShopName, ShopTempPath = queue.ShoptempPath };
                    }
                    else if (queue.Status == intWait)//如果是等待状态 要检查满对列表
                    {

                        List<UploadQueue> listQueue = db.UploadQueue.Where(qu => qu.Status == intDiong).ToList();

                        if (listQueue.Count > inMaxQueueNum)//检查是否过连接数
                        {
                            queue.Status = intWait;

                        }
                        else
                        {
                            queue.Status = intDiong;
                        }
                        rtnInfo = new TransferFileInfo() { Name = inFileName, Status = intDiong, CreateTime = queue.CreateTime, Length = queue.FileLength, ShopName = queue.ShopName, ShopTempPath = queue.ShoptempPath};

                    }
                    else if (queue.Status == intStop)
                    {
                        //rtnInfo = new TransferFileInfo() { Name = inFileName, Status = intDiong, CreateTime = queue.CreateTime, Length = queue.FileLength, ShopName = queue.ShopName,Remark="文件已经上传不要重复上传" };
                        List<UploadQueue> listQueue = db.UploadQueue.Where(qu => qu.Status == intDiong).ToList();

                        if (listQueue.Count > inMaxQueueNum)//检查是否过连接数
                        {
                            queue.Status = intWait;

                        }
                        else
                        {
                            queue.Status = intDiong;
                        }
                        rtnInfo = new TransferFileInfo() { Name = inFileName, Status = intDiong, CreateTime = queue.CreateTime, Length = queue.FileLength, ShopName = queue.ShopName, ShopTempPath = queue.ShoptempPath }; ;
                    }
                }
                else//上传列表不存在
                {
                    UploadQueue newQueue = new UploadQueue();
                    int shopID = Convert.ToInt32(inFileName.Substring(1, 4));
                    //Shop shop = db.Shop.FirstOrDefault();
                    List<UploadQueue> listQueue = db.UploadQueue.Where(qu => qu.Status == intDiong).ToList();

                    newQueue.Shop = db.Shop.FirstOrDefault(sh => sh.ShopId == shopID);
                    newQueue.ShopName = newQueue.Shop.shopName;
                    newQueue.ZipName = inFileName;
                    newQueue.CreateTime = DateTime.Now;
                    newQueue.CompleteTime = DateTime.Now;
                    newQueue.FileLength = Convert.ToInt32(inFileLength);
                    //FileInfo file = new FileInfo(GetSavePath() + "\\" + inFileName); 
                    newQueue.Remark = "";
                    newQueue.MachineName = ininfo.MachineName;
                    newQueue.ShoptempPath = ininfo.ShopTempPath;
                    if (listQueue.Count > inMaxQueueNum)//检查是否过连接数
                    {
                        newQueue.Status = intWait;

                    }
                    else
                    {
                        newQueue.Status = intDiong;
                    }

                    db.AddToUploadQueue(newQueue);//添加进数据列表中
                    rtnInfo = new TransferFileInfo() { Name = inFileName, Status = intDiong, CreateTime = newQueue.CreateTime, Length = inFileLength, ShopName = newQueue.ShopName, ShopTempPath = newQueue.ShoptempPath };
                }

                db.SaveChanges();

            }
            return rtnInfo;
        }
        /// <summary>
        /// 获取正在传输文件的列表
        /// </summary>
        /// <returns></returns>
        public List<TransferFileInfo> GetFilesList(int inShopID)
        {
            string SavePath = GetSavePath();

            List<TransferFileInfo> listFile = new List<TransferFileInfo>();
            int status = (int)TransferStatus.Doing;
            int stopStatus = (int)TransferStatus.Stop;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                string strShopid = inShopID.ToString().PadLeft(4, '0');
                List<UploadQueue> listUpload = db.UploadQueue.Where(uq => (uq.ZipName.Substring(1, 4)).Equals(strShopid) && (uq.Status == status||uq.Status==stopStatus)).ToList();
                foreach (UploadQueue uque in listUpload)
                {
                    TransferFileInfo info = new TransferFileInfo();
                    info.Name = uque.ZipName;
                    info.CreateTime = uque.CreateTime;
                    info.Length = uque.FileLength;
                    info.MachineName = uque.MachineName;
                    //info.GuagaPresent = "0";

                    FileInfo file = new FileInfo(SavePath + "\\" + uque.ZipName);
                    if (file.Exists)
                    {
                        info.Offset = file.Length;//获取到文件的大小
                    }
                    else
                    {
                        info.Offset = 0;
                    }
                    info.ShopName = uque.ShopName;
                    info.ShopTempPath = uque.ShoptempPath;
                    info.Status = uque.Status;
                    listFile.Add(info);
                }
            }
            return listFile;

        }
        /// <summary>
        /// 客户端正在上传的数量
        /// </summary>
        /// <returns></returns>
        public int GetTransferingFileCount()
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int Uploading = (int)TransferStatus.Doing;
                return db.UploadQueue.Where(u => u.Status == Uploading).Count();
            }
        }
        /// <summary>
        /// 获取上传文件信息
        /// </summary>
        /// <param name="inFileName"></param>
        /// <returns></returns>
        public UploadInfo GetUploadingFileInfo(string inFileName)
        {
            UploadInfo rtnInfo = new UploadInfo();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                UploadQueue up = db.UploadQueue.FirstOrDefault(u => u.ZipName == inFileName);
                rtnInfo.ZipName = inFileName;
                rtnInfo.CreateTime = up.CreateTime;
                rtnInfo.FileLength = up.FileLength;
                rtnInfo.Status = up.Status;
                rtnInfo.ShopName = up.ShopName;

            }
            return rtnInfo;
        }
        /// <summary>
        /// 完成上传
        /// </summary>
        public void CompleteUpload(string inFileName)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                UploadQueue que = db.UploadQueue.FirstOrDefault(p => p.ZipName == inFileName);
                if (que != null)
                {
                    que.Status = (int)TransferStatus.Done;
                    que.CompleteTime = DateTime.Now;
                }
                db.SaveChanges();
            }

        }
        /// <summary>
        /// 根据状态获取等待上传的列表
        /// </summary>
        /// <returns></returns>
        public List<UploadInfo> GetUploadList(int status)
        {
            List<UploadInfo> unList = new List<UploadInfo>();

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                
                List<UploadQueue> list = db.UploadQueue.Where(p => p.Status == status).ToList();
                foreach (UploadQueue que in list)
                {
                    UploadInfo info = new UploadInfo();
                    info.ZipName = que.ZipName;
                    info.Status = que.Status;
                    info.CreateTime = que.CreateTime;
                    info.FileLength = que.FileLength;
                    info.ShopName = que.ShopName;
                    info.CompleteTime = que.CompleteTime;
                    unList.Add(info);
                }

            }
            return unList;
        }
        /// <summary>
        /// 创建上传记录
        /// </summary>
        /// <param name="inInfo"></param>
        /// <returns>-1错误，0正常，1已经存在</returns>
        public int CreateUploadQueue(TransferFileInfo inInfo)
        {
            int rtnVal = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    UploadQueue existuq = db.UploadQueue.FirstOrDefault(p => p.ZipName == inInfo.Name);
                    if (existuq != null)
                    {
                        rtnVal = 1;//上传列表已经存在
                    }
                    UploadQueue uq = new UploadQueue();
                    uq.CompleteTime = inInfo.CreateTime;
                    uq.CreateTime = inInfo.CreateTime;
                    uq.FileLength = (int)inInfo.Length;
                    uq.MachineName = inInfo.MachineName;
                    uq.orderbagid = 0;
                    uq.Shop = db.Shop.FirstOrDefault(p => p.ShopId == inInfo.ShopID);
                    uq.ShopName = inInfo.ShopName;
                    uq.ShoptempPath = inInfo.ShopTempPath;
                    uq.ZipName = inInfo.Name;
                    uq.Remark = "";
                    uq.Status = (int)TransferStatus.Wait;
                    db.AddToUploadQueue(uq);
                    db.SaveChanges();
                    rtnVal = 0;

                }
            }
            catch
            {
                rtnVal = -1;
            }
            return rtnVal;
        }
        /// <summary>
        /// 暂停上传
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int StopUploadQueue(TransferFileInfo info)
        {
            int rtnVal = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    UploadQueue uq = db.UploadQueue.FirstOrDefault(p => p.ZipName == info.Name);
                    uq.Status = (int)TransferStatus.Stop;
                    db.SaveChanges();
                    rtnVal = 1;
                }
            }
            catch
            {
                rtnVal = -1;
            }
            return rtnVal;
        }
        /// <summary>
        /// 删除掉暂停的上传列表
        /// </summary>
        /// <param name="ininfo"></param>
        /// <returns></returns>
        public int DeleteUploadQueue(TransferFileInfo ininfo)
        {
            int rtnVal = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    UploadQueue uq = db.UploadQueue.FirstOrDefault(p => p.ZipName == ininfo.Name);
                    uq.Status = (int)TransferStatus.Delete;

                    db.SaveChanges();
                    rtnVal = 1;
                }
            }
            catch
            {
                rtnVal = -1;
            }
            return rtnVal;
        }
    }
}
